/**
 * @copyright fpx.com 
 */
package com.fpx.open.platform.interceptor;

import java.util.Date;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContext;

import com.fpx.open.platform.common.constant.AppConstant;
import com.fpx.open.platform.common.constant.BaseConstant;
import com.fpx.open.platform.common.constant.SysConstant;
import com.fpx.open.platform.common.util.HttpUtil;
import com.fpx.open.platform.common.util.JsonBinder;
import com.fpx.open.platform.domain.ActionLog;
import com.fpx.open.platform.web.manager.ActionLogManager;

/**
 * 访问日志拦截器,记录每次访问api的请求参数和返回参数
 *
 * @author sunkey
 * @date Apr 24, 2013 10:05:34 AM
 * @version 1.0.0 
 */
public class LogHandlerInterceptor implements HandlerInterceptor {
	
	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Resource
	private ActionLogManager actionLogManager;
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		request.setAttribute(AppConstant.REQ_LOG_DATE, new Date());
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
//		logger.info("============"+modelAndView.getModelMap().get("resultVo"));
		
//		HandlerMethod handlerMethod = (HandlerMethod) handler;
//		BaseController baseController = (BaseController)handlerMethod.getBean();
//		System.out.println(baseController.getRequestAttribute(AppConstant.REQ_USERID));
//		MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
//		ModelMap modelMap = modelAndView.getModelMap();
//		for (String key : modelMap.keySet()) {
//			System.out.println(key + ": " + modelMap.get(key));
//		}
		

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// 记录日志
		String customerId = HttpUtil.getParameter(request, BaseConstant.COOPERATION_ID);
		String token = HttpUtil.getParameter(request, BaseConstant.COOPERATION_TOKEN);
		String format = HttpUtil.getFormat(request);
		

		RequestContext requestContext = new RequestContext(request);
		Locale locale = requestContext.getLocale();

		HandlerMethod handlerMethod = null;
		String method = null;
		Integer userId = null;
		
		try {
			if(handler instanceof HandlerMethod){
				handlerMethod = (HandlerMethod) handler;
				method = "";
				userId = 123;
				
			} else {
				method = "unknown method";
			}
			if(StringUtils.isBlank(token)){
				token = (String)request.getAttribute(BaseConstant.COOPERATION_TOKEN);
			}
			if(StringUtils.isBlank(token)){
				token = "no token";
			}
			Object responseContent =  request.getAttribute(AppConstant.RESP_CONTENT);
			String reqContent = (String) request.getAttribute(AppConstant.REQ_CONTENT);
			
			Date reqLogDate = ((Date)request.getAttribute(AppConstant.REQ_LOG_DATE));
			recordLog(reqLogDate, token, responseContent, "{userId:" + userId + ",customerId:" + customerId + ",language:" + locale
					+ ",format:" + format + "}," + reqContent, method,
					SysConstant.STATUS_SUCCESS);
		} catch (Exception e1) {
			logger.error("record log failer", e1);
		}

	}
	
	
	/**
	 * 记录日志
	 * 
	 * @param token 用户令牌
	 * @param responseContent 返回结果
	 * @param reqVo 请求的实体
	 */
	private void recordLog(Date reqLogDate, String token, Object responseContent, String reqVo,
			String method, int status) {
		ActionLog actionLog = new ActionLog();
		actionLog.setDateRequest(reqLogDate);
		actionLog.setCustomerToken(token);
		actionLog.setInterfaceName(method);
		actionLog.setReqContent(reqVo);
		actionLog.setRespContent(JsonBinder.buildNonDefaultBinder().toJson(
				responseContent));
		actionLog.setDateResponse(new Date());
		actionLog.setStatus(status);
		actionLogManager.saveActionLog(actionLog);
	}


}
